<template>
  <el-dialog
    v-model="visible"
    title="编辑用户"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="用户头像">
            <div class="avatar-container">
              <el-avatar :src="getFullImageUrl(formData.avatar_url)" :size="80">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
              <div class="avatar-info">
                <p>头像URL:</p>
                <el-input v-model="formData.avatar_url" placeholder="请输入头像URL" />
                <div class="image-url-display" style="color: #888; font-size: 12px; margin-top: 2px;">
                  实际图片地址：{{ getFullImageUrl(formData.avatar_url) }}
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%">
              <el-option label="未知" :value="0" />
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户状态" prop="is_active">
            <el-switch
              v-model="formData.is_active"
              active-text="活跃"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 自定义属性 -->
      <el-form-item label="自定义属性">
        <div class="attributes-section">
          <div class="attributes-header">
            <span>管理用户的自定义属性</span>
            <el-button type="primary" size="small" @click="handleAddAttribute">
              <el-icon><plus /></el-icon>
              添加属性
            </el-button>
          </div>
          
          <div v-if="attributes.length > 0" class="attributes-list">
            <div
              v-for="(attr, index) in attributes"
              :key="index"
              class="attribute-item"
            >
              <el-input
                v-model="attr.key"
                placeholder="属性名"
                style="width: 120px"
              />
              <span class="separator">:</span>
              <el-input
                v-model="attr.value"
                placeholder="属性值"
                style="flex: 1"
              />
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveAttribute(index)"
              >
                <el-icon><delete /></el-icon>
              </el-button>
            </div>
          </div>
          <el-empty v-else description="暂无自定义属性" :image-size="60" />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserDetail, updateUser } from '@/api/user'

export default {
  name: 'UserEditDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'updated'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)
    const loading = ref(false)
    const formRef = ref(null)
    
    // 表单数据
    const formData = reactive({
      nickname: '',
      phone: '',
      gender: 0,
      is_active: true,
      avatar_url: ''
    })

    // 属性数据
    const attributes = ref([])

    // 表单验证规则
    const rules = {
      nickname: [
        { required: true, message: '请输入用户昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ]
    }

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val && props.user) {
        initFormData()
        fetchUserAttributes()
      }
    })

    watch(visible, (val) => {
      emit('update:modelValue', val)
    })

    // 初始化表单数据
    const initFormData = () => {
      Object.assign(formData, {
        nickname: props.user.nickname || '',
        phone: props.user.phone || '',
        gender: props.user.gender || 0,
        is_active: props.user.is_active !== false,
        avatar_url: props.user.avatar_url || ''
      })
    }

    // 获取用户属性
    const fetchUserAttributes = async () => {
      try {
        const response = await getUserDetail(props.user.id)
        const userAttributes = response.data.attributes || {}
        
        attributes.value = Object.entries(userAttributes).map(([key, value]) => ({
          key,
          value
        }))
      } catch (error) {
        console.error('获取用户属性失败:', error)
      }
    }

    // 添加属性
    const handleAddAttribute = () => {
      attributes.value.push({
        key: '',
        value: ''
      })
    }

    // 删除属性
    const handleRemoveAttribute = (index) => {
      attributes.value.splice(index, 1)
    }

    // 获取完整图片URL
    const getFullImageUrl = (url) => {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) {
        return url;
      }
      const backendUrl = 'https://dpcurdgwzmkg.sealosbja.site';
      const relativeUrl = url.startsWith('/') ? url : `/${url}`;
      return `${backendUrl}${relativeUrl}`;
    }

    // 提交表单
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
      } catch (error) {
        return
      }

      loading.value = true
      try {
        // 准备更新数据
        const updateData = { ...formData }
        
        // 处理属性数据
        const attributesData = {}
        attributes.value.forEach(attr => {
          if (attr.key && attr.value) {
            attributesData[attr.key] = attr.value
          }
        })
        updateData.attributes = attributesData

        await updateUser(props.user.id, updateData)
        
        ElMessage.success('用户信息更新成功')
        emit('updated')
        handleClose()
      } catch (error) {
        ElMessage.error('更新失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      
      // 重置表单
      nextTick(() => {
        formRef.value?.resetFields()
        attributes.value = []
      })
    }

    return {
      visible,
      loading,
      formRef,
      formData,
      attributes,
      rules,
      initFormData,
      fetchUserAttributes,
      handleAddAttribute,
      handleRemoveAttribute,
      handleSubmit,
      handleClose,
      getFullImageUrl
    }
  }
}
</script>

<style scoped>
.avatar-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-info {
  flex: 1;
}

.avatar-info p {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.attributes-section {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.attributes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.attributes-header span {
  color: #606266;
  font-size: 14px;
}

.attributes-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.attribute-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.separator {
  margin: 0 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 新增：修复弹窗内容溢出问题 */
:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}

.image-url-display {
  word-break: break-all;
}
</style> 